package service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import model.MResource;
import model.MResourceType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.interf.IResource;

import common.impl.exception.ServiceException;

import dao.interf.IAuthorityDAO;
import dao.interf.IResourceAuthorityDAO;
import dao.interf.IResourceDAO;
import dao.interf.IResourceTypeDAO;
import dao.pojo.Authority;
import dao.pojo.Resource;
import dao.pojo.ResourceAuthority;
import dao.pojo.ResourceType;

public class ResourceImpl implements IResource{

	IResourceAuthorityDAO rAuthDao;
	IResourceTypeDAO typeDao;
	IResourceDAO resourceDao;
	IAuthorityDAO authDao;
	
	public void setAuthDao(IAuthorityDAO authDao) {
		this.authDao = authDao;
	}
	public void setResourceDao(IResourceDAO resourceDao) {
		this.resourceDao = resourceDao;
	}
	public void setrAuthDao(IResourceAuthorityDAO rAuthDao) {
		this.rAuthDao = rAuthDao;
	}
	public void setTypeDao(IResourceTypeDAO typeDao) {
		this.typeDao = typeDao;
	}

	/**
	 * 获取所有资源和权限
	 */
	public Map<String, ArrayList<String>> findAllResourcesWithAuth()
			throws RuntimeException {
		Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(0);
		ArrayList<String> arr = new ArrayList<String>(0);
		List<ResourceAuthority> ralst= rAuthDao.findAll();
		if(!ralst.isEmpty()) {
			for(Iterator<ResourceAuthority> it = ralst.iterator(); it.hasNext();) {
				ResourceAuthority ra = it.next();
				Authority auth = ra.getAuthority();
				Resource res = ra.getResource();
				if(map.get(res.getUrl()) == null) {
					arr = new ArrayList<String>(0);
				}
				arr.add(auth.getAuthorityName());
				map.put(res.getUrl(), arr);
			}
		}
		return map;
	}
	
	
	
	/* 添加资源
	 * @return resoureId
	 * 		资源id
	 * @see service.interf.IResource#addResource(model.MResource)
	 */
	public String addResource(MResource model) throws Exception {
		Resource r = new Resource();
		r.setUrl(model.getUrl());
		ResourceType rt = typeDao.findById(model.getResourceTypeId());
		r.setResourceType(rt);
		r = resourceDao.save(r);
		return r.getResourceId().toString();
	}
	/* (添加资源类型
	 * @see service.interf.IResource#addResourceType(model.MResourceType)
	 */
	public String addResourceType(MResourceType model) throws Exception {
		ResourceType rt = new ResourceType();
		rt.setResourceTypeName(model.getResourceTypeName());
		rt = typeDao.save(rt);
		return rt.getResourceTypeId().toString();
	}
	/* 通过导入文件批量添加资源
	 * @see service.interf.IResource#batchReourceByFile(java.util.List)
	 */
	public String batchReourceByFile(List<File> fl) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	/* 批量更新资源
	 * @see service.interf.IResource#batchUpdate(java.lang.String)
	 */
	public String batchUpdate(String datas) throws Exception {
		JSONArray jarr = JSONArray.fromObject(datas);
		for(int i=0,len=jarr.size(); i<len; i++){
			JSONObject jobj = jarr.getJSONObject(i);
			int flag = jobj.getInt("flag");
			switch(flag){
			case 1: //添加
				String url = jobj.getString("url");
				Resource resource = new Resource();
				resource.setUrl(url);
				ResourceType resourceType = new ResourceType();
				resourceType.setResourceTypeId(jobj.getInt("resourceTypeId"));
				resource.setResourceType(resourceType);
				resourceDao.save(resource);
				break;
			case 2:  //编辑
				Resource eResource = new Resource();
				eResource.setUrl(jobj.getString("url"));
				eResource.setResourceId(jobj.getInt("resourceId"));
				ResourceType rType = new ResourceType();
				rType.setResourceTypeId(jobj.getInt("resourceTypeId"));
				eResource.setResourceType(rType);
				resourceDao.update(eResource);
				break;
			case 3:  //删除
				int ResourceId = jobj.getInt("resourceId");
				resourceDao.delById(ResourceId);
			}
		}
		return "1";
	}
	/* 批量更新资源类型
	 * @see service.interf.IResource#batchUpdateType(java.lang.String)
	 */
	public String batchUpdateType(String datas) throws Exception {
		JSONArray jarr = JSONArray.fromObject(datas);
		for(int i=0,len=jarr.size();i<len;i++){
			JSONObject jobj = jarr.getJSONObject(i);
			int flag = jobj.getInt("flag");
			switch(flag){
			case 1: //添加
				String resourceTypeName = jobj.getString("resourceTypeName");
				ResourceType resourceType = new ResourceType();
				resourceType.setResourceTypeName(resourceTypeName);
				typeDao.save(resourceType);
				break;
			case 2:  //编辑
				String rTypeName = jobj.getString("resourceTypeName");
				ResourceType rType = new ResourceType();
				rType.setResourceTypeName(rTypeName);
				rType.setResourceTypeId(jobj.getInt("resourceTypeId"));
				typeDao.update(rType);
				break;
			case 3:  //删除
				int ResourceTypeId = jobj.getInt("resourceTypeId");
				typeDao.delById(ResourceTypeId);
			}
		}
		return "1";
	}
	/* 删除资源
	 * @see service.interf.IResource#delResource(model.MResource)
	 */
	public String delResource(MResource model) throws Exception {
		resourceDao.delById(model.getResourceId());
		return "1";
	}
	/* (删除资源类型
	 * @see service.interf.IResource#delResourceType(model.MResourceType)
	 */
	public String delResourceType(MResourceType model) throws Exception {
		typeDao.delById(model.getResourceTypeId());
		return "1";
	}
	/* 编辑资源
	 * @see service.interf.IResource#editResource(model.MResource)
	 */
	public String editResource(MResource model) throws Exception {
		Resource r = null;
		r = resourceDao.findById(model.getResourceId());
		if(null == r) {
			throw new ServiceException("ERR-0091");
		}
		r.setResourceId(model.getResourceId());
		r.setUrl(model.getUrl());
		ResourceType rt = typeDao.findById(model.getResourceTypeId());
		r.setResourceType(rt);
		resourceDao.update(r);
		return "1";
	}
	/* 编辑资源类型
	 * @see service.interf.IResource#editResourceType(model.MResourceType)
	 */
	public String editResourceType(MResourceType model) throws Exception {

		ResourceType rt = null;
		rt = typeDao.findById(model.getResourceTypeId());
		if(null == rt) {
			throw new ServiceException("ERR-0091");
		}
		rt.setResourceTypeId(model.getResourceTypeId());
		rt.setResourceTypeName(model.getResourceTypeName());
		typeDao.update(rt);
		return "1";
	
	}
	
	//=========================查找====================================
	
	/* 查找所有资源
	 * @see service.interf.IResource#findAllResources(boolean, int, int)
	 */
	public String findAllResources(boolean detail, int pageno, int pagesize)
			throws Exception {
		Map<String, Object> map = new HashMap<String,Object>(0);
		List<Resource> lst = null;
		lst = resourceDao.findAll();
		JSONArray jarr = new JSONArray();
		for(Resource r : lst) {
			JSONObject jobj = new JSONObject();
			jobj.put("resourceId",   r.getResourceId());
			jobj.put("resourceName", r.getResourceName());
			if(null != r.getResourceType()) {
				jobj.put("resourceTypeId", r.getResourceType().getResourceTypeId());
				jobj.put("resourceTypeName", r.getResourceType().getResourceTypeName());
			}
			jobj.put("url", r.getUrl());
			jarr.add(jobj);
		}
		JSONObject jret = new JSONObject();
		jret.put("rows", jarr);
		return jret.toString();
	}//debug pass
	
	/* 查找所有资源类型
	 * @see service.interf.IResource#findAllType()
	 */
	public String findAllType() throws Exception {
		List<ResourceType> lst = typeDao.findAll();
		JSONArray jarr = new JSONArray();
		if (null != lst ){
			for (ResourceType l : lst) {
				JSONObject jobj = new JSONObject();
				jobj.put("resourceTypeId", l.getResourceTypeId());
				jobj.put("resourceTypeName", l.getResourceTypeName());
				jarr.add(jobj);
			}
		}
		JSONObject jret = new JSONObject();
		jret.put("rows", jarr.toString());
		return jret.toString();
	}//debug pass
	
	/* 通过资源id查找资源
	 * @see service.interf.IResource#findResourceById(java.lang.Integer)
	 */
	public String findResourceById(Integer resourceId) throws Exception {
		Resource r = null;
		r = resourceDao.findById(resourceId);
		if(null == r) {
			throw new ServiceException("ERR-0091");
		}
		JSONObject jobj = new JSONObject();
		jobj.put("resourceId", r.getResourceId());
		jobj.put("resourceName", r.getResourceName());
		jobj.put("url", r.getUrl());
		ResourceType rt = r.getResourceType();
		if(null != rt) {
			jobj.put("resourceTypeId", rt.getResourceTypeId());
			jobj.put("resourceTypeName", rt.getResourceTypeName());
		}
		return jobj.toString();
	}
	
	/* 通过资源类型查找资源
	 * @see service.interf.IResource#findResourcesByType(java.lang.Integer, boolean, int, int)
	 */
	public String findResourcesByType(Integer typeId, boolean detail,
			int pageno, int pagesize) throws Exception {
		ResourceType rt = null;
		rt = typeDao.findById(typeId);
		if(null == rt) {
			throw new ServiceException("ERR-0092");
		}
		List<Resource> lst = null;
		lst = resourceDao.findByProperties(new String[] {"typeid"},
				new Object[] {typeId});
		JSONArray jarr = new JSONArray();
		for (Resource r : lst) {
		    JSONObject jobj = new JSONObject();
		    jobj.put("resourceId",   r.getResourceId());
		    jobj.put("resourceName", r.getResourceName());
		    if(null != r.getResourceType()) {
		    	jobj.put("resourceTypeId", r.getResourceType().getResourceTypeId());
		    	jobj.put("resourceTypeName", r.getResourceType().getResourceTypeName());
		    }
		    jobj.put("url", r.getUrl());
		    jarr.add(jobj);
		}
		JSONObject jret = new JSONObject();
		jret.put("rows", jarr);
		return jret.toString();
	}
	/* 通过资源id,获取资源的所有权限
	 * @see service.interf.IResource#getResourceAuthorities(java.lang.Integer)
	 */
	public String getResourceAuthorities(Integer resourceId) throws Exception {
		Resource r  = null;
		r = resourceDao.findById(resourceId);
		if(null == r) {
			throw new ServiceException("ERR-0091");
		}
		Map<String, Object> map = new HashMap<String, Object>(0);
		map.put("resource", r);
		List<ResourceAuthority> lst = rAuthDao.findByProperties(map);
		JSONArray jarr = new JSONArray();
			for(ResourceAuthority ra : lst) {
				JSONObject jobj = new JSONObject();
				if(null != ra.getAuthority()) {
					jobj.put("authorityId", ra.getAuthority().getAuthorityId());
					jobj.put("authorityName", ra.getAuthority().getAuthorityName());
				}
				jarr.add(jobj);
			}
		JSONObject jret = new JSONObject();
		jret.put("rows", jarr);
		return jret.toString();
	}//debug pass
	
	/* 通过权限获取所有资源
	 * @see service.interf.IResource#getResourceByAuth(java.lang.String)
	 */
	public String getResourceByAuth(Integer authorityId) throws Exception {
		Authority auth = authDao.findById(authorityId);
		if(null == auth) {
			throw new ServiceException("ERR-0091");
		}
		List<ResourceAuthority> ralst = rAuthDao.findByProperties(new String[]{"authorityid"},
				new Object[] { authorityId });
		JSONArray jarr = new JSONArray();
		if(null != ralst){
			for(ResourceAuthority ra : ralst){
				JSONObject jobj = new JSONObject();
				jobj.put("authorityId",   ra.getAuthority().getAuthorityId());
				jobj.put("authorityName", ra.getAuthority().getAuthorityName());
				jobj.put("resourceId",    ra.getResource().getResourceId());
				jobj.put("resourceName",  ra.getResource().getResourceName());
				if(null != ra.getResource().getResourceType()) {
					jobj.put("resourceTypeId",  ra.getResource().getResourceType().getResourceTypeId());
					jobj.put("resourceTypeName",  ra.getResource().getResourceType().getResourceTypeName());
				}
				jobj.put("url", ra.getResource().getUrl());
				jarr.add(jobj);
			}
		}
		JSONObject jret = new JSONObject();
		jret.put("rows", jarr);		
		return jret.toString();
	}
	/* 更新指定权限的所有资源
	 * @see service.interf.IResource#updateAuthorityResources(java.lang.String, java.lang.String)
	 */
	public String updateAuthorityResources(Integer authorityId,
			String authorityResources) throws Exception {
		//串以逗号隔开,第一个为authId，后面依次为多个资源
		String[] datas = authorityResources.split(",");
		int len = 0 ;
		if(null == datas || (len = datas.length) < 1)
			throw new ServiceException("ERR-0091");
		Authority auth = authDao.findById(authorityId);
		if(null == auth) {
			throw new ServiceException("ERR-0091");
		}
		Map<String,Object> map = new HashMap<String,Object>(0);
		map.put("authority", auth);
		//删除
	    rAuthDao.delByProperties(map);
		for(int i=0; i<len; i++){
			Resource r = resourceDao.findById(new Integer(datas[i]));
			if(null == r) {
				throw new ServiceException("ERR-0091");
			}
			ResourceAuthority ra = new ResourceAuthority();
			ra.setAuthority(auth);
			ra.setResource(r);
			rAuthDao.save(ra);
		}
		return "1";
	}
	/* 更新指定资源的所有权限
	 * @see service.interf.IResource#updateResourceAuthority(java.lang.String)
	 */
	public String updateResourceAuthority(String resourceAuthorities)
			throws Exception {
		//串以逗号隔开,第一个为resourceId，后面依次为多个权限id
		String[] rdata = resourceAuthorities.split(",");
		int len = 0;
		if(rdata == null || (len=rdata.length)<1) {
			throw new ServiceException("ERR-0091");
		}
		int rid = Integer.parseInt(rdata[0]);
		Resource r = null;
		r = resourceDao.findById(rid);
		if(null == r) {
			throw new ServiceException("ERR-0091");
		}
		Map<String, Object> map = new HashMap<String, Object>(0);
		map.put("resource", r);
		//删除资源权限中资源为r的所有权限
		rAuthDao.delByProperties(map);
		ArrayList<String> arr = new ArrayList<String>();
		for(int i=1; i<len; i++){
			Authority a = null;
			a = authDao.findById(Integer.parseInt(rdata[i]));
			if(a != null){
				ResourceAuthority ra = new ResourceAuthority();
				ra.setAuthority(a);
				ra.setResource(r);
				rAuthDao.save(ra);
				//资源权限保存
				arr.add(a.getAuthorityName());
			}
		}
		//修改资源内存权限
		security.MyInvocationSecurityMetadataSource.changeAuthority(r.getUrl(), arr);
		return "1";
	}//debug pass

}
